﻿using Lhz.Common.Business;
using Lhz.Sc.Entity.Database;
using Lhz.Sc.Entity.Enum;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Lhz.Sc.Business
{
    public class AuthorizationProxy : EntityProxy<Guid, Authorization>
    {
        public AuthorizationProxy(string pathConfiguration = null) : base(pathConfiguration)
        {

        }

        public bool Check(Application application, Service service, Operation operation, Guid userGuid)
        {
            var authorizations = CreateQueryable().QueryByUserGuid(userGuid).ToList();
            if (authorizations.Any(r => r.AuthorizationType == AuthorizationType.ApplicationAuthorization && r.ObjectGuid == application.Guid))
            {
                return true;
            }
            if (authorizations.Any(r => r.AuthorizationType == AuthorizationType.ServiceAuthorization && r.ObjectGuid == service.Guid))
            {
                return true;
            }
            if (authorizations.Any(r => r.AuthorizationType == AuthorizationType.OperationAuthorization && r.ObjectGuid == operation.Guid))
            {
                return true;
            }
            return false;
        }

        public List<Authorization> QueryByUserGuid(Guid userGuid)
        {
            return CreateQueryable().QueryByUserGuid(userGuid).ToList();
        }

        public void DeleteByUserGuid(Guid userGuid)
        {
            var authorizations = QueryByUserGuid(userGuid);
            Delete(authorizations);
        }
    }
}
